package com.shrfid.rfidsdk.tag.base;

import com.rfid.common.log.LogUtils;
import com.shrfid.module_base.entity.TagEntity;
import com.shrfid.rfidsdk.tag.inter.ICommand;
import com.shrfid.rfidsdk.uitls.ReadTagUtils;

import java.util.Arrays;
import java.util.List;


public abstract class BaseDecoder<R extends BaseCommand, T extends BaseResponseFrame, F extends BaseResponseData> implements ICommand {

    protected DecodeListener listener;
    protected ReaderListener readerListener;

    protected T responseFrame;
    protected R baseCommand;
    protected F responseData;

    private BaseDecoder() {

    }

    public BaseDecoder(R baseCommand) {
        this.baseCommand = baseCommand;
    }

    protected  void decodeResponse(T frame) {
        if (responseData == null) {
            responseData = createResponseData();
        }
        if (responseData != null) {
            //解析响应数据帧
            responseData.parseFrame(frame);
            if (responseData.isComplete()) {
                if (readerListener != null) {
                    readerListener.onTagRead(frame.toBytes());
                }
                if (responseData.getData() != null) {
                    LogUtils.v(Arrays.toString(responseData.getData().toArray()));
                } else {
                    LogUtils.v("read no  tag");
                }
                if (listener != null) {
                    listener.onTagResult(responseData.getData());
                }
                responseData = null;
            }
        }
    }

    @Override
    public byte[] connectDevice() {
        return baseCommand.connectDevice();
    }

    @Override
    public byte[] inventory() {
        return baseCommand.inventory();
    }

    @Override
    public byte[] writeAfi(byte[] uid, byte afi) {
        return baseCommand.writeAfi(uid, afi);
    }

    @Override
    public byte[] optionPower(byte power) {
        return baseCommand.optionPower(power);
    }


    @Override
    public byte[] selectAntenna(int antenna) {
        return baseCommand.selectAntenna(antenna);
    }

    @Override
    public byte[] setEas(byte[] uid) {
        return baseCommand.setEas(uid);
    }

    @Override
    public byte[] resetEas(byte[] uid) {
        return baseCommand.resetEas(uid);
    }

    public void setListener(DecodeListener listener) {
        this.listener = listener;
    }

    public void setReaderListener(ReaderListener readerListener) {
        this.readerListener = readerListener;
    }

    public abstract F createResponseData();

    public abstract void decode(byte[] data);

    public interface DecodeListener {

        void onTagResult(List<TagEntity> data);
    }

    public interface ReaderListener {

        void onTagRead(byte[] data);
    }
}
